#include <ProcessTerminationEvent.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>



ProcessTerminationEvent::ProcessTerminationEvent(int process_count_)
{
	process_count = process_count_;
	acc_status = 0;
	if( pthread_mutex_init(&mutex, NULL) || pthread_cond_init(&condition, NULL) ){
		perror("Could not initialize termination event.");
		exit(-1);
	}
}

ProcessTerminationEvent::~ProcessTerminationEvent()
{}

void 
ProcessTerminationEvent::IncrementProcessCount()
{
	pthread_mutex_lock(&mutex);
	process_count++;
	pthread_mutex_unlock(&mutex);
}

void 
ProcessTerminationEvent::Trigger(int exit_status)
{
	pthread_mutex_lock(&mutex);
	process_count--;
	if( process_count < 1 ){
		pthread_cond_signal(&condition);
	}
	if( exit_status ){
		acc_status = exit_status;
	}
	pthread_mutex_unlock(&mutex);
}

int
ProcessTerminationEvent::WaitForProcessTermination()
{
	pthread_mutex_lock(&mutex);
	while(process_count > 0){
		pthread_cond_wait(&condition, &mutex);	
	}
	pthread_mutex_unlock(&mutex);
	return acc_status;
}



